﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Crm.CrmClient;

namespace Crm
{
    public partial class Login : Page
    {
        CrmClient.CrmServiceClient client = new CrmClient.CrmServiceClient();

        public Login()
        {
            InitializeComponent();
            this.Loaded += Login_Loaded;
            client.KullaniciGirisCompleted += client_KullaniciGirisCompleted;
            this.txtKullanici.KeyDown += txtKullanici_KeyDown;
            this.txtSifre.KeyDown += txtSifre_KeyDown;
        }

        void txtSifre_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                client.KullaniciGirisAsync(txtKullanici.Text, txtSifre.Password);
            }
        }

        void txtKullanici_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key== Key.Enter)
            {
                txtSifre.Focus();
            }
        }

        void Login_Loaded(object sender, RoutedEventArgs e)
        {
            System.Windows.Browser.HtmlPage.Plugin.Focus();
            txtKullanici.Focus();
        }

        void client_KullaniciGirisCompleted(object sender, CrmClient.KullaniciGirisCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else
            {
                Kullanici usr = e.Result;
                if (e.Result != null)
                {
                    Session.Instance.Add("user", usr);
                    this.LayoutRoot.RowDefinitions.Clear();
                    this.LayoutRoot.ColumnDefinitions.Clear();
                    this.LayoutRoot.Children.Clear();
                    this.LayoutRoot.Children.Add(new MainPage());
                }
                else
                {
                    MessageBox.Show("Kullanıcı bulunamadı !");
                }
            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnGiris_Click(object sender, RoutedEventArgs e)
        {
            client.KullaniciGirisAsync(txtKullanici.Text, txtSifre.Password);
        }

    }
}
